/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zoe.onelink.actuate.endpoint;

import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.zoe.onelink.util.IpUtil;
import com.zoe.onelink.util.SpringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-07-15
 */
@RequiredArgsConstructor
@Slf4j
@Endpoint(id = "shutdown", enableByDefault = false)
public class OnelinkShutdownEndpoint extends ShutdownEndpoint {

    private static final Map<String, String> NO_CONTEXT_MESSAGE = Collections.singletonMap("message", "No context to shutdown.");

    private static final Map<String, String> SHUTDOWN_MESSAGE = Collections.singletonMap("message", "Shutting down, bye...");

    private ConfigurableApplicationContext context;
    private final int nacosCloseWaitMillis;

    /**
     * @ReadOperation：作用在方法上，可用来返回端点展示的信息（通过 Get 方法请求）。
     * @WriteOperation：作用在方法上，可用来修改端点展示的信息（通过 Post 方法请求）。
     * @DeleteOperation：作用在方法上，可用来删除对应端点信息（通过 Delete 方法请求）。
     * @Selector：作用在参数上，用来定位一个端点的具体指标路由
     */
    @SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    @Override
    @WriteOperation
    public Map<String, String> shutdown() {
        Set<String> localIps = this.getLocalIps();
        log.info("[优雅停机] 接收到停机事件,开始关闭服务.本机IP地址列表: {}", localIps);
        if (this.context == null) {
            return NO_CONTEXT_MESSAGE;
        }
        Thread thread = new Thread(this::performShutdown);
        thread.setContextClassLoader(getClass().getClassLoader());
        thread.start();
        return SHUTDOWN_MESSAGE;
    }

    /**
     * 获取本地IP地址列表
     */
    private Set<String> getLocalIps() {
        try {
            LinkedHashSet<String> ips = IpUtil.localIpv4s();
            ips.remove("127.0.0.1");
            ips.remove("localhost");
            return ips;
        } catch (Exception e) {
            log.error("[优雅停机] 获取本地IP列表失败", e);
        }
        return Collections.emptySet();
    }

    private void performShutdown() {
        try {
            log.info("[优雅停机] 开始注销Nacos实例...");
            SpringUtil.getBean(NacosAutoServiceRegistration.class).destroy();
            log.info("[优雅停机] Nacos实例注销成功,等待{}毫秒后开始停止服务", this.nacosCloseWaitMillis);
            Thread.sleep(this.nacosCloseWaitMillis);
        } catch (InterruptedException ex) {
            log.error("[优雅停机] 关闭注销Nacos实例出现异常: {}", ex.getMessage());
            ex.printStackTrace();
            Thread.currentThread().interrupt();
        }
        log.info("[优雅停机] 开始关闭容器上下文");
        this.context.close();
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        if (context instanceof ConfigurableApplicationContext) {
            this.context = (ConfigurableApplicationContext) context;
        }
    }

}
